/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.msu.common;

import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.msu.api.MsuService;
import io.iec.edp.caf.msu.api.ServiceUnitAwareService;
import io.iec.edp.caf.msu.api.client.ServiceDiscovery;
import io.iec.edp.caf.msu.api.entity.ServiceUnitInfo;
import io.iec.edp.caf.msu.api.enums.DeployMode;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Leon Huo
 */
public class MsuServiceImpl implements MsuService {

    private ServiceUnitAwareService suAware;

    //系统微服务感知服务
    private ServiceDiscovery serviceDiscovery;

    public MsuServiceImpl(ServiceUnitAwareService suAware, ServiceDiscovery serviceDiscovery) {
        this.suAware = suAware;
        this.serviceDiscovery = serviceDiscovery;
    }

    @Override
    public DeployMode getDeployMode(String appServerName) {
        return CafEnvironment.getEnvironment().getProperty("msu.deployMode", DeployMode.class, DeployMode.OnPremise);
    }

    @Override
    public boolean isLocalInvoke(String serviceUnitName) {
        return this.suAware.getEnabledServiceUnits().stream().anyMatch(d -> d.equalsIgnoreCase(serviceUnitName));
    }

    @Override
    public List<ServiceUnitInfo> getEnabledServiceUnit() {
        List<ServiceUnitInfo> infos = this.serviceDiscovery.getEnabledServiceUnitInfo();
        if (infos != null && infos.size() > 0) {
            infos = infos.stream().filter(x -> !x.getName().endsWith("-grpc")).collect(Collectors.toList());
        }

        return infos;
    }

}
